using Domain.DTOs.排程;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using Team.API.Applocation.Command.排程;
using Team.API.Hubs;

namespace Team.API.Services
{
    /// <summary>
    /// 生产计划后台服务
    /// 每分钟自动获取并推送生产计划数据
    /// </summary>
    public class ProductionScheduleBackgroundService : BackgroundService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IHubContext<EquipmentStatusHub> _hubContext;
        private readonly ILogger<ProductionScheduleBackgroundService> _logger;
        private readonly TimeSpan _interval = TimeSpan.FromMinutes(1); // 每分钟执行一次

        public ProductionScheduleBackgroundService(
            IServiceProvider serviceProvider,
            IHubContext<EquipmentStatusHub> hubContext,
            ILogger<ProductionScheduleBackgroundService> logger)
        {
            _serviceProvider = serviceProvider;
            _hubContext = hubContext;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("生产计划推送服务已启动");

            // 延迟10秒后开始执行，避免与设备状态检查冲突
            await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await FetchAndPushProductionSchedule(stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取并推送生产计划时发生错误");
                }

                // 等待1分钟后再次执行
                await Task.Delay(_interval, stoppingToken);
            }

            _logger.LogInformation("生产计划推送服务已停止");
        }

        /// <summary>
        /// 获取并推送生产计划数据
        /// </summary>
        private async Task FetchAndPushProductionSchedule(CancellationToken cancellationToken)
        {
            using var scope = _serviceProvider.CreateScope();
            var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();

            var currentTime = DateTime.Now;
            _logger.LogInformation($"开始获取生产计划数据 - {currentTime:yyyy-MM-dd HH:mm:ss}");

            try
            {
                // 调用GetProductionCommand获取生产计划
                var request = new GetProductionCommand();
                var result = await mediator.Send(request, cancellationToken);

                if (result != null && result.ListResult != null)
                {
                    _logger.LogInformation($"成功获取 {result.Totalcount} 条生产计划记录");

                    // 通过SignalR推送生产计划数据给所有客户端
                    await _hubContext.Clients.All.SendAsync(
                        "ReceiveProductionScheduleUpdate",
                        new
                        {
                            Time = currentTime,
                            TotalCount = result.Totalcount,
                            Data = result.ListResult,
                            Message = $"生产计划已更新，共 {result.Totalcount} 条记录",
                            Source = "定时刷新"
                        },
                        cancellationToken);

                    _logger.LogInformation("生产计划数据已通过SignalR推送");
                }
                else
                {
                    _logger.LogWarning("获取生产计划返回空数据");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产计划失败");
                
                // 推送错误消息
                await _hubContext.Clients.All.SendAsync(
                    "ReceiveProductionScheduleError",
                    new
                    {
                        Time = currentTime,
                        Message = $"获取生产计划失败: {ex.Message}",
                        Source = "定时刷新"
                    },
                    cancellationToken);
            }
        }
    }
}
